package com.zhenyi.tuangou.admin.index;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.cenjiawen.common.IndexController;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.api.MediaFile;
import com.utils.PathUtils;
import com.utils.image.UploadUtils;

import cn.hutool.json.JSONObject;

public class ApiController extends IndexController {

	public void upload() {
		File file = getFileParam("file");

		if (!file.exists()) {
			renderMsg("文件不存在");
			return;
		}
		String url = UploadUtils.upload(file);
		System.out.println(url);
		if (url != null) {
			renderResult(url);
		} else {
			renderFailure(500, "上传失败");
		}
	}

	public void uploadEditorImg() {
		File file = getFileParam("file");
		JSONObject result = new JSONObject();

		if (!file.exists()) {
			result.put("error", 1);
			result.put("message", "上传失败！");
			renderJson(result);
		}
		String url = UploadUtils.upload(file);
		if (url != null) {
			result.put("error", 0);
			result.put("url", url);
			renderJson(result);
		} else {
			result.put("error", 1);
			result.put("message", "文件不存在！");
			renderFailure();
		}
	}
	
	public void uploadWXImage() {
		String mediaId = getPara("mediaId");
		System.out.println(mediaId);
		// System.out.println(file.exists());
		// InputStream inputStream = MediaApi.getMaterial(mediaId);
		MediaFile mediaFile = MediaApi.getMedia(mediaId);
		System.out.println(mediaFile.getError());
		System.out.println(mediaFile.getContentLength());
		System.out.println(mediaFile.getContentType());
		String fileName = mediaFile.getFileName() + "sss.png";
		System.out.println(fileName);
		File file = new File(PathUtils.getFile("upload", fileName));
		BufferedInputStream stream = mediaFile.getFileStream();
		try {
			inputStreamToFile(stream, file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String url = UploadUtils.upload(file);
		System.out.println(url);
		renderResult(url);
	}

	private void inputStreamToFile(InputStream ins, File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
	}

}
